use actix::{ActorContext, Handler, Message, Recipient};

use super::{webrtc::WebrtcServer, webrtc_session::WebrtcSession};

#[derive(Message)]
#[rtype(result = "()")]
pub struct SessionMessage(pub String, pub bool);

#[derive(Message)]
#[rtype(result = "()")]
pub struct WebrtcConnection {
    pub id: usize,
    pub reci: Recipient<SessionMessage>,
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct WebrtcDisConnection {
    pub id: usize,
}

#[derive(Message)]
#[rtype(result = "()")]
pub struct WebrtcMessage {
    pub id: usize,
    pub msg: String,
}

impl Handler<WebrtcMessage> for WebrtcServer {
    type Result = ();
    fn handle(&mut self, msg: WebrtcMessage, ctx: &mut Self::Context) -> Self::Result {
        let json: serde_json::Value = serde_json::from_str(&msg.msg).unwrap();

        println!("{}", msg.msg);
        println!("{:?}", json);
        if json.get("join").is_some() {
            let id: usize = json.get("join").unwrap().as_u64().unwrap() as usize;
            println!("peerId:{:?}", id);
            self.map.insert(msg.id, id);
            self.map.insert(id, msg.id);
            if let Some(r) = self.sessions.get(&id) {
                let _ = r.do_send(SessionMessage(msg.msg, true));
            }
        } else {
            //判断有没有关联
            if self.map.contains_key(&msg.id) {
                let json_id = self.map.get(&msg.id).unwrap();
                if let Some(r) = self.sessions.get(json_id) {
                    let _ = r.do_send(SessionMessage(msg.msg, true));
                }
            }
        }
    }
}

impl Handler<WebrtcConnection> for WebrtcServer {
    type Result = ();
    fn handle(&mut self, msg: WebrtcConnection, ctx: &mut Self::Context) -> Self::Result {
        self.sessions.insert(msg.id, msg.reci);
    }
}

impl Handler<WebrtcDisConnection> for WebrtcServer {
    type Result = ();
    fn handle(&mut self, msg: WebrtcDisConnection, ctx: &mut Self::Context) -> Self::Result {
        if let Some(reci) = self.sessions.get(&msg.id) {
            reci.do_send(SessionMessage("dis".to_string(), false));
        }
    }
}

impl Handler<SessionMessage> for WebrtcSession {
    type Result = ();
    fn handle(&mut self, msg: SessionMessage, ctx: &mut Self::Context) -> Self::Result {
        if (msg.1) {
            ctx.text(msg.0);
        } else {
            ctx.stop();
        }
    }
}
